import {
  Component,
  OnInit,
  ViewChild,
  Optional,
  Inject,
  Output,
  EventEmitter,
  OnChanges,
  ChangeDetectorRef,
} from '@angular/core';
import { SchoolService } from 'src/app/ytt/services/school.service';
import { SchoolDTO } from 'src/app/ytt/model/school-dto';
import { ElementBase } from 'src/app/ytt/util/form/element-base';
import { NG_VALUE_ACCESSOR, NgModel, NG_VALIDATORS, NG_ASYNC_VALIDATORS } from '@angular/forms';
import { NzTreeNode } from 'ng-zorro-antd';
import { CollectionHelper } from 'src/app/ytt/util/data/collection-helper';

@Component({
  selector: 'app-school-select',
  templateUrl: './school-select.component.html',
  styleUrls: ['./school-select.component.less'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: SchoolSelectComponent,
      multi: true,
    },
  ],
})
export class SchoolSelectComponent extends ElementBase<Array<SchoolDTO>> implements OnInit, OnChanges {
  /**
   * model的实例
   */
  @ViewChild(NgModel, null)
  model: NgModel;

  /**
   * 勾选事件
   */
  @Output()
  checkedEvent = new EventEmitter();

  /**
   * 请求状态
   */
  isLoading = false;

  /**
   * 下拉初始数据
   */
  nodes = [];

  /**
   * 树节点数组
   */
  treeNodes: Array<NzTreeNode> = [];

  /**
   * 单个树节点对象
   */
  treeNode: NzTreeNode;

  /**
   * 树节点对象
   */
  data = null;

  constructor(
    private schoolService: SchoolService,
    @Optional() @Inject(NG_VALIDATORS) validators: Array<any>,
    @Optional() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: Array<any>,
  ) {
    super(validators, asyncValidators);
  }

  ngOnInit() {
    this.load();
  }

  load() {
    this.isLoading = true;
    this.schoolService.getAll().subscribe(
      data => {
        if (data) {
          this.nodes = data;
        }
      },
      null,
      () => {
        this.isLoading = false;
      },
    );
  }

  /**
   * 选择事件
   * @param $event 选择的值 选择的值 多选下返回的是数组
   */
  select($event) {
    this.treeNodes = [];
    if (typeof $event === 'string') {
      if (this.value) {
        this.treeNode = CollectionHelper.findTreeItem(this.nodes, $event, 'key');
        if (this.treeNode) {
          this.treeNodes.push(this.treeNode);
        }
        this.data = { value: this.value, treeNodes: this.treeNodes };
        this.checkedEvent.emit(this.data);
      }
    } else {
      if ($event && $event.length !== 0) {
        this.value.forEach(el => {
          const itemId = el;
          this.treeNode = CollectionHelper.findTreeItem(this.nodes, itemId, 'key');

          if (this.treeNode) {
            this.treeNodes.push(this.treeNode);
          }
        });
        this.data = { value: this.value, treeNodes: this.treeNodes };
        this.checkedEvent.emit(this.data);
      }
    }
  }

  /**
   * 传入参数变化时的处理
   * @param changes 变化的参数
   */
  ngOnChanges(changes) {
    console.log(1);
  }

  writeValue(value: Array<any>) {
    super.writeValue(value);
  }
}
